import requests
import time
import re
import threading
import concurrent.futures
import pandas as pd

res = {}

# 定义接口 URL
POST_URL = "https://log_center.smyoa.com/api/v1/jobs"
GET_URL_TEMPLATE = "https://log_center.smyoa.com/api/v1/jobs/{}/events?order=desc&pageNo=1&pageSize=10&prefix=&rawLenLimit=true&sort=updateTime"

# 定义请求头
HEADERS = {
    "Cookie": "JSESSIONID=MzlkNjg4MDktZWM1NC00MTNmLWE4ODQtZmE5ZTQzNjI1NDY0LHgwMTUzOCxERW43ZWNxUUVIK3dYZ3FNeU53ZWQ4RkEyb009",
    "Content-Type": "application/json",
     "x-csrf-token" : "f781e3a7-7c45-4c3f-b640-b9561369fae0"
}

# 定义 POST 请求的入参模板
POST_DATA_TEMPLATE = {
    "app": "",
    "source": "search",
    "query": 'repo="smy_mlp_core" "/tencent/behavior/v3" "{}"',
    "startTime": 1750953600000,
    "endTime": 1751039999000,
    "mode": "smart",
    "preview": True,
    "collectSize": 500,
    "timeout": -1,
    "sorts": []
}


# 获取风控模板
POST_PCR_TEMPLATE = {
    "app": "",
    "source": "search",
    "query": 'repo="smy_mms_core" AND "queryPcrApplyInfoByCustNo" "{}"',
    "startTime": 1742918400000,
    "endTime": 1743004799000,
    "mode": "smart",
    "preview": True,
    "collectSize": 500,
    "timeout": -1,
    "sorts": []
}

# 定义需要匹配的关键字
KEYWORD = "新浪半流程API-授信申请-注册结果："

def post_request(half_register_response):
    """
    发送 POST 请求并获取响应的 id
    """
    # 更新 POST 请求体中的 HalfRegisterResponse 值
    post_data = POST_DATA_TEMPLATE.copy()
    post_data["query"] = post_data["query"].format(half_register_response)

    # 发送 POST 请求
    response = requests.post(POST_URL, json=post_data, headers=HEADERS)
    if response.status_code != 200:
        raise Exception(f"POST 请求失败，状态码：{response.status_code}, 响应内容：{response.text}")

    # 解析响应，获取 id
    result = response.json()
    job_id = result.get("id")
    if not job_id:
        raise Exception("未获取到有效的 job id")
    return job_id

def post_pcr_request(custNo):
    """
    发送 POST 请求并获取响应的 id
    """
    # 更新 POST 请求体中的 HalfRegisterResponse 值
    post_data = POST_PCR_TEMPLATE.copy()
    post_data["query"] = post_data["query"].format(custNo)

    # 发送 POST 请求
    response = requests.post(POST_URL, json=post_data, headers=HEADERS)
    if response.status_code != 200:
        raise Exception(f"POST 请求失败，状态码：{response.status_code}, 响应内容：{response.text}")

    # 解析响应，获取 id
    result = response.json()
    job_id = result.get("id")
    if not job_id:
        raise Exception("未获取到有效的 job id")
    return job_id


def get_events(job_id):
    """
    根据 job_id 获取事件列表
    """
    get_url = GET_URL_TEMPLATE.format(job_id)
    response = requests.get(get_url, headers=HEADERS)
    print(f"GET 获取报文内容：{response.text}")
    if response.status_code != 200:
        raise Exception(f"GET 请求失败，状态码：{response.status_code}, 响应内容：{response.text}")

    return response.json()


def extract_data(response_data):
    """
    从响应数据中提取目标数据
    """
    data = str(response_data)
    if 'L03|BEGIN' in data:
        print(f'获取到关键数据' + data )
        fixed_part = '|/mlp/tencent/behavior/v3||[GET]'
        start_index = data.find(fixed_part)
        if start_index != -1:
          # 找到固定部分后，从 '?' 开始取到最后

          query_params = data[start_index + len(fixed_part):]
          end = query_params.find('\\n')
          return query_params[0:end]
        else:
          print('未找到地址')
    return None

def extract_pcr_data(response_data):
    """
    从响应数据中提取目标数据
    """
    data = str(response_data)
    if 'awordResultCode' in data:
        print(f'获取到关键数据' + data )
        # 定义正则表达式
        pattern = r"\"awordResultCode\":\"([^\"]+)\""

        # 查找匹配项
        match = re.search(pattern, data)
        if match:
           return match.group(1)  # 返回捕获组中的值
    return None

success = []
fail = []
def main(half_register_response):
    """
    主函数，执行整个流程
    """
    try:
        # Step 1: 发送 POST 请求，获取 job id
        job_id = post_request(half_register_response)
        print(f"成功获取 job id: {job_id}")

        # Step 2: 轮询 GET 接口，直到找到包含关键字的响应
        count = 0
        while True:
            if(count > 2):
                print(f"超过最大次数，请检查数据{half_register_response}")
                fail.append(half_register_response)
                break
            response_data = get_events(job_id)
            extracted_data = extract_data(response_data)
            if extracted_data:
                print(f"成功提取数据：{extracted_data}")
                res = requests.get('https://gateway.smyfinancial.com' + extracted_data)
                print(f"调用结果:{res.text}")
                return extracted_data

            # 等待一段时间后继续轮询
            count = count + 1
            time.sleep(5)

    except Exception as e:
        print(f"发生错误：{e}")



def sendData(k) :
    m = main(k)
    if m is not None:
        success.append(k)


if __name__ == "__main__":
    max_work = 30
    # 示例参数变量
    #data = ['2gx65swurtbtw01','2himvjyu4ojjc01','2hsljqeeln4oe01']
    df = pd.read_excel('test.xlsx',engine='openpyxl')
    data = df.iloc[:, 0].dropna().tolist()  # 去掉空值

    with concurrent.futures.ThreadPoolExecutor(max_work) as executor:
        futures = [executor.submit(sendData, k) for k in data]
    print(f"成功操作的数据：{success}")
    print(f"成功数量：{len(success)}")
    print(f"失败操作的数据：{fail}")
    print(f"失败数量：{len(fail)}")




